package com.example.gustavo.hello.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;


import java.util.ArrayList;
import java.util.List;

/**
 * Created by gustavo on 2015/8/12.
 */
public class MyHorizontalScrollView extends HorizontalScrollView {

    private ScrollViewObserver scrollViewObserver = new ScrollViewObserver();

    public MyHorizontalScrollView(Context context) {
        super(context);
    }

    public MyHorizontalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyHorizontalScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {

        if (scrollViewObserver != null) {
            scrollViewObserver.notifyChanged(l, t, oldl, oldt);
        }

        super.onScrollChanged(l, t, oldl, oldt);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return super.onTouchEvent(ev);
    }

    public void addOnScrollChangedListener(OnScrollChangedListener onScrollChangedListener) {
        scrollViewObserver.addOnScrollChangedListener(onScrollChangedListener);
    }
    public void removeOnScrollChangedListener(OnScrollChangedListener onScrollChangedListener){
        scrollViewObserver.removeOnScrollChangedListener(onScrollChangedListener);
    }


    public interface OnScrollChangedListener{
        void onScrollChanged(int l, int t, int oldl, int oldt);
    }

    public static class OnScrollChangedListenerImp implements OnScrollChangedListener{

        private HorizontalScrollView horizontalScrollView;
        public OnScrollChangedListenerImp(HorizontalScrollView hsv) {
            horizontalScrollView = hsv;
        }

        @Override
        public void onScrollChanged(int l, int t, int oldl, int oldt) {
            if (horizontalScrollView != null) {
                horizontalScrollView.smoothScrollTo(l, t);
            }
        }
    }

    public static class ScrollViewObserver{
        private List<OnScrollChangedListener> listeners = new ArrayList<>();


        public void addOnScrollChangedListener(OnScrollChangedListener onScrollChangedListener){

            listeners.add(onScrollChangedListener);
        }
        
        public void removeOnScrollChangedListener(OnScrollChangedListener onScrollChangedListener){
            listeners.remove(onScrollChangedListener);
        }
        
        public void notifyChanged(int l, int t, int oldl, int oldt){

            for (OnScrollChangedListener listener : listeners) {

                if (listener != null) {
                    listener.onScrollChanged(l, t, oldl, oldt);
                }

            }
        }
    }

}
